﻿using System;
using System.Net;
using System.Diagnostics;
using System.Windows.Forms;
using System.Xml.Linq;
using ClrExtensions.Net.Rest;
using ClrExtensions.Security.OAuth;
using MediaPortal.GUI.Library;

namespace MyNetflix2
{
    public class Connection : MyNetFlixData
    {
        #region Locals & Public

        //------------------------------------------------------------------------------------
        // You need to get a developer account at Netflix to get the Consumer Key and Secret
        //------------------------------------------------------------------------------------
        private readonly string _consumerKey = "";
        private readonly string _consumerSecret = "";
        private AccessToken _accessToken = new AccessToken();

        /// <summary>
        /// The Consumer Key of the Application
        /// </summary>
        public string ConsumerKey
        {
            get { return _consumerKey; }
        }
        /// <summary>
        /// The Consumer Secret of the Applciation
        /// </summary>
        public string ConsumerSecret
        {
            get { return _consumerSecret; }
        }
        /// <summary>
        /// The Token used to make user requests
        /// </summary>
        public AccessToken NetFlixAccessToken
        {
            get { return _accessToken; }
            set { _accessToken = value; }
        }


        #endregion

        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        public Connection()
        {
        }

        #endregion

        /// <summary>
        /// Generate the Request Token for the User
        /// </summary>
        public void GenerateRequestToken(string userId)
        {
            User user;

            //--------------------------------------------------------------------------------
            // Lets see if the user is already got a token...
            //--------------------------------------------------------------------------------
            if (!base.GetQueueUser(userId))
            {
                try
                {
                    //--------------------------------------------------------------------------------
                    // Generate the call request
                    //--------------------------------------------------------------------------------
                    RestCall call = RestCalls.RequestToken().SignRestCall(_consumerKey, _consumerSecret);
                    HttpWebRequest request = call.CreateHttpWebRequest();

                    //--------------------------------------------------------------------------------
                    // Get the response from the stream
                    //--------------------------------------------------------------------------------
                    WebResponse response = request.GetResponse();
                    string data = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();

                    //--------------------------------------------------------------------------------
                    // Set up the request token
                    //--------------------------------------------------------------------------------
                    RequestToken requestToken = new RequestToken(data, this);


                    //--------------------------------------------------------------------------------
                    // Now prompt the user for their Netflix credentials
                    //--------------------------------------------------------------------------------
                    Process.Start(requestToken.PermissionURL);

                    //--------------------------------------------------------------------------------
                    // Pop up a dialog to wait for the user to register with Netflix.
                    //--------------------------------------------------------------------------------
                    DialogResult dr = MessageBox.Show("Have you entered your credentials?", "Credentials", MessageBoxButtons.YesNo);

                    if (dr == DialogResult.Yes)
                    {
                        //--------------------------------------------------------------------------------
                        // If they accept then get the token and write it to the database.
                        //--------------------------------------------------------------------------------
                        _accessToken = requestToken.ConvertToAccessToken();

                        user = new User(_accessToken, this);
                        user.GetUser();

                        if (!base.GetQueueUser(user.FirstName))
                        {
                            base.UserName = user.FirstName;
                            base.UserId = _accessToken.UserId;
                            base.AccessToken = _accessToken.Token;
                            base.AccessTokenSecret = _accessToken.TokenSecret;
                            base.AddQueueUser();
                            Log.Info("My NetFlix - Authorize:NetFlixAuthorize: User now registered.");
                        }
                        else
                            Log.Info("My NetFlix - Authorize:NetFlixAuthorize: User {0} already registered.", user.FirstName);
 
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("My NetFlix - Authorize:NetFlixAuthorize: Error -", ex.Message);
                }
            }
            else
            {
                //--------------------------------------------------------------------------------
                // The user is already registered, lets use the current redentials from the DB.
                //--------------------------------------------------------------------------------
                _accessToken = new AccessToken(base.UserId, base.AccessToken, base.AccessTokenSecret);
                Log.Info("My NetFlix - Authorize:NetFlixAuthorize: User is registered.");
            }

            //user = new User(_accessToken, this);
            //Queue jQueue = null;
            //jQueue = new RSS(user);
            //jQueue.GetTop(-1);
            //jQueue = new Recommendations(user);
            //jQueue.Refresh();
            //jQueue = new Episodes(user);
            //jQueue.Refresh("http://api.netflix.com/catalog/titles/series/70157523/seasons/70039852/episodes");
            //jQueue.Refresh("http://api.netflix.com/catalog/titles/series/70140405/seasons");
            //oDataCalls calls = new oDataCalls();

            //Queue jQueue = null;

            //jQueue = new oDataCalls(user);
            //jQueue.Refresh("http://odata.netflix.com/Catalog/Genres('Comedy')/Titles?$filter=Instant/AvailableFrom lt datetime'2011-04-19'&$orderby=year(Instant/AvailableFrom)&$top=200");

            //jQueue = new InstantQueue(user);

            //jQueue = new InstantQueue(user);
            //jQueue.Refresh();
            //iQueue.Add("http://api.netflix.com/catalog/titles/movies/60020905", RestCalls.DiscFormat.DVD, 1);


        }

        /// <summary>
        /// Convert the request to an access token the app can use to make calls
        /// </summary>
        /// <param name="requestToken"></param>
        /// <returns></returns>
        public AccessToken ConvertRequestToAccessToken(RequestToken requestToken)
        {
            try
            {
                //--------------------------------------------------------------------------------
                // Set up the Rest call
                //--------------------------------------------------------------------------------
                RestCall call = RestCalls.GetAccessToken().SignRestCall(_consumerKey, _consumerSecret, requestToken.Token, requestToken.TokenSecret);
                HttpWebRequest request = call.CreateHttpWebRequest();

                //--------------------------------------------------------------------------------
                // Submit and get the response from the stream
                //--------------------------------------------------------------------------------
                WebResponse response = request.GetResponse();
                string data = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();

                return new AccessToken(data);
            }
            catch (System.Net.WebException ex)
            {
                Log.Error("My NetFlix - Connection:ConvertRequestToAccessToken: Error - " + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// Request an XML Resource
        /// </summary>
        /// <param name="resource"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public XElement RequestXmlResource(RestCall resource, AccessToken accessToken)
        {
            return XElement.Parse(RequestResource(resource, accessToken));
        }

        /// <summary>
        /// Request a resource
        /// </summary>
        /// <param name="resource"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public string RequestResource(RestCall resource, AccessToken accessToken)
        {
            //--------------------------------------------------------------------------------
            // Set up the Rest call
            //--------------------------------------------------------------------------------
            RestCall call = resource.SignRestCall(_consumerKey, _consumerSecret, accessToken.Token, accessToken.TokenSecret);
            HttpWebRequest request = call.CreateHttpWebRequest();
            request.ContentLength = 0;

            //--------------------------------------------------------------------------------
            // Send the request and get the response from the stream
            //--------------------------------------------------------------------------------
            try
            {
                System.Net.WebResponse response = request.GetResponse();
                return new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();
            }
            catch (System.Net.WebException ex)
            {
                Log.Error("My NetFlix - Connection:RequestResource: Error - " + ex.Message);
                return null;
            }

        }
    }
}
